import checkLogin from "./checkLogin";
import {baseUrl} from "./config";

const toast = (title, reject) => {
    wx.showToast({
        title,
        icon: 'none'
    })
    reject(title)
}

/**
 * Promise 风格网络请求工具
 * @param url String 请求的url
 * @param method String 请求方法
 * @param data Object 请求的参数
 * @returns {Promise<unknown>}
 */
const request = (url, method = 'GET', data = {}, isLoading = true) => {
    return new Promise((resolve, reject) => {
        if(isLoading) {
            wx.showLoading({
                title: '加载中..'
            })
        }
        
        wx.request({
            url: baseUrl + url,
            method,
            data,
            header: {
                Authorization: 'Bearer ' + wx.getStorageSync('access_token') || ''
            },
            success(res) {
                const {statusCode} = res
                let msg = ''

                // 请求成功, 成功返回数据的情况
                if (statusCode < 400) {
                    resolve(res.data)
                } else if (statusCode == 400) {
                    msg = res.data.message
                } else if (statusCode == 401) {
                    // 账号密码错误
                    if (res.data.message == "Unauthorized") {
                        msg = '账号或密码错误'
                    } else {
                        // 未登录, token过期
                        wx.removeStorageSync('access_token')
                        wx.removeStorageSync('userInfo')
                        // 跳转到登录页面
                        checkLogin()
                    }
                } else if (statusCode == 403) {
                    msg = '没有权限'
                } else if (statusCode == 404) {
                    msg = '未找到资源'
                } else if (statusCode == 422) {
                    const {errors} = res.data
                    msg = errors[Object.keys(errors)[0]].pop()
                } else if (statusCode == 429) {
                    msg = '请稍后再试'
                } else {
                    msg = '请求异常'
                }

                if (msg) toast(msg, reject)
            },
            fail() {
                toast('服务器异常', reject)
            },
            complete() {
                wx.hideLoading()
            }
        })
    })
}

const e = {
    request,
    get: (url, data = {}, isLoading = true) => request(url, 'GET', data, isLoading),
    post: (url, data = {}, isLoading = true) => request(url, 'POST', data, isLoading),
    put: (url, data = {}, isLoading = true) => request(url, 'PUT', data, isLoading),
    patch: (url, data = {}, isLoading = true) => {
        // 因为小程序的请求工具不支持patch方式, 所以要模拟patch的请求
        // 在请求参数中, 追加 _method: "PATCH" 即可模拟patch请求
        // 模拟请求必须使用 post 方式提交
        data = {
            ...data,
            _method: 'PATCH'
        }
       return request(url, 'POST', data, isLoading)
    },
    delete: (url, data = {}, isLoading = true) => request(url, 'DELETE', data, isLoading),
}

module.exports = e